﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using EzDesk.DesktopClient.Storage;
using EzDesk.DesktopClient.ViewContract;
using EzDesk.Generic.WPF;
using EzDesk.MVVMBase;

namespace EzDesk.DesktopClient.View
{
    /// <summary>
    /// Interaction logic for LoginView.xaml
    /// </summary>
    public partial class LoginView : UserControl, ILoginView
    {

        object IView.ViewModel
        {
            get { return ViewModel; }
            set { ViewModel = (ILoginViewModel) value; }
        }

        public ILoginViewModel ViewModel
        {
            get
            {
                return this.DataContext as ILoginViewModel;
            }
            set
            {
                this.DataContext = value;
            }
        }
        public LoginView()
        {
            InitializeComponent();
            this.Dispatcher.BeginInvoke(new Action(this.Init));
        }

        private void Init()
        {
            FocusUserNameTextBox();

        }

        private void FocusUserNameTextBox()
        {
            UserName_Tbx.Focus();
        }

        protected void OnLogin_Btn_Click(object sender, EventArgs e)
        {
            DoLogin();
        }

        private void DoLogin()
        {
            ViewModel.Login(UserName_Tbx.Text,Password_Tbx.Password);
            Keyboard.ClearFocus();
        }

        public void LoginFailed()
        {
            LoginMessage_Tbx.Show();
            FocusUserNameTextBox();
        }


        private void UserName_Tbx_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                DoLogin();
            }
        }

        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            FocusUserNameTextBox();
        }

        private void ClearLocalDB_Click(object sender, RoutedEventArgs e)
        {
            ClientDbStorage.ClearLocalDatabase();
        }

        
    }
}
